<?php

namespace App\Rpc\Traits\Service;

use App\Lib\Error\ErrorConstant;
use App\Lib\Error\Response;
use App\Rpc\Model\Dao\ModuleDao;
use App\Rpc\Model\Dao\PackageDao;
use App\Rpc\Model\Dao\TenantDao;
use App\Rpc\Model\Dao\TenantPermissionsDao;
use App\Rpc\Model\Dao\UserDao;
use App\Rpc\Model\Logic\PermissionLogic;
use phpDocumentor\Reflection\DocBlock\Tags\Param;
use Swoft\Bean\BeanFactory;
use Swoft\Db\DB;
use Swoft\Validator\Exception\ValidatorException;

/**
 * Trait TenantTrait
 * @package App\Rpc\Traits
 */
trait TenantTrait
{
    /**
     * 添加租户
     * @param array $data
     * @return array
     */
    public function tenantCreate(array $data): array
    {
        try{

            $name = $data['name']??null;
            $prefix = $data['prefix']??null;

            //验证字段
            $required = [
                'user_item_id' => '请输入用户item_id',
                'identity_id' => '请输入身份类型',
                'name' => '请输入租户名称',
                'prefix' => '请输入租户前缀（英文）',
                'account' => '请输入租户账号',
                'password' => '请输入租户账号登录密码',
                're_password' => '请输入租户账号确认登录密码',
                'package_id' => '请输入套餐id',
                'unit' =>  '请输入套餐时间计量单位',
                'num' => '请输入套餐时长'
            ];

            foreach ($required as $key => $require) {
                if(!isset($data[$key]) || empty($data[$key])){
                    throw new ValidatorException($require, 4002);
                }
            }

            //判断下密码
            if($data['password'] !== $data['re_password']){
                throw new ValidatorException('两次输入密码不同，请重新输入', 4002);
            }

            /** @var PermissionLogic $PermissionLogic */
            $PermissionLogic = BeanFactory::getBean(PermissionLogic::class);
            $result = $PermissionLogic->tenantCreate($data);
            return Response::Info($result);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 添加套餐
     * @param array $data
     * @return array
     */
    public function packageCreate(array $data): array
    {
        try{
            $name = $data['name']??null;
            $description = $data['description']??null;

            if(!$name){
                Response::FatalError(ErrorConstant::VALIDATE_ERROR_CODE, '请求参数错误');
            }
            $data['item_id'] = create_item_id(uuid());

            /** @var PermissionLogic $PermissionLogic */
            $PermissionLogic = BeanFactory::getBean(PermissionLogic::class);
            $result = $PermissionLogic->packageCreate($data);
            return Response::Info($result);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 模块添加
     * @param array $data
     * @return array
     */
    public function moduleCreate(array $data): array
    {
        try{
            $name = $data['name']??null;
            $module_value = $data['module_value']??null;

            if(!$name || !$module_value){
                Response::FatalError(ErrorConstant::VALIDATE_ERROR_CODE, '请求参数错误');
            }
            $data['item_id'] = create_item_id(uuid());

            /** @var PermissionLogic $PermissionLogic */
            $PermissionLogic = BeanFactory::getBean(PermissionLogic::class);
            $result = $PermissionLogic->moduleCreate($data);
            return Response::Info($result);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 租户权限添加
     * @param array $data
     * @return array
     */
    public function tenantPermissionsCreate(array $data): array
    {
        try{
            //租户权限名称
            $name = $data['name']??null;
            //权限value
            $permission_value = $data['permission_value']??null;

            if(!$name || !$permission_value){
                Response::FatalError(ErrorConstant::VALIDATE_ERROR_CODE, '请求参数错误');
            }

            //参数组装
            $data['item_id'] = create_item_id(uuid());
            $data['type'] = $data['type']??'menu';
            $data['parent_item_id'] = $data['parent_item_id']??'0';
            $data['purpose'] = $data['purpose']??1;

            /** @var PermissionLogic $PermissionLogic */
            $PermissionLogic = BeanFactory::getBean(PermissionLogic::class);
            $result = $PermissionLogic->tenantPermissionsCreate($data);
            return Response::Info($result);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 套餐添加模块等
     * @param array $data
     * @return array
     */
    public function packageModifyModules(array $data): array
    {
        try{
            $package_item_id = $data['package_item_id']??null;
            //加入套餐的模块id
            $attached_module_item_ids = $data['attached_module_item_ids']??[];

            //移除套餐的模块id
            $detached_module_item_ids = $data['detached_module_item_ids']??[];

            if(!$package_item_id || (!$attached_module_item_ids && !$detached_module_item_ids)){
                Response::FatalError(ErrorConstant::VALIDATE_ERROR_CODE, '请求参数错误');
            }

            $data['item_id'] = create_item_id(uuid());

            /** @var PermissionLogic $PermissionLogic */
            $PermissionLogic = BeanFactory::getBean(PermissionLogic::class);
            $result = $PermissionLogic->packageModifyModules($data);
            return Response::Info($result);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 模块添加权限等
     * @param array $data
     * @return array
     */
    public function moduleModifyPermissions(array $data): array
    {
        try{
            $module_item_id = $data['module_item_id']??null;
            //授权套餐id
            $attached_permission_item_ids = $data['attached_permission_item_ids']??[];

            //接触套餐id
            $detached_permission_item_ids = $data['detached_permission_item_ids']??[];

            if(!$module_item_id || (!$attached_permission_item_ids && !$detached_permission_item_ids)){
                Response::FatalError(ErrorConstant::VALIDATE_ERROR_CODE, '请求参数错误');
            }

            $data['item_id'] = create_item_id(uuid());

            /** @var PermissionLogic $PermissionLogic */
            $PermissionLogic = BeanFactory::getBean(PermissionLogic::class);
            $result = $PermissionLogic->moduleModifyPermissions($data);
            return Response::Info($result);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 根据module_id获取权限
     * @param array $data
     * @return array
     */
    public function modulePermissions(array $data): array {
        try {
            //验证字段
            $required = [
                'user_item_id' => '请输入用户item_id',
                'identity_id' => '请输入身份类型',
                'module_id' => '请输入模块item_id',
            ];

            foreach ($required as $key => $require) {
                if(!isset($data[$key]) || empty($data[$key])){
                    throw new ValidatorException($require, 4002);
                }
            }

            /** @var PermissionLogic $PermissionLogic */
            $PermissionLogic = BeanFactory::getBean(PermissionLogic::class);
            $result = $PermissionLogic->modulePermissions($data);
            return Response::Info($result);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 根据package_id获取模块列表
     * @param array $data
     * @return array
     */
    public function packageModules(array $data): array {
        try {
            //验证字段
            $required = [
                'user_item_id' => '请输入用户item_id',
                'identity_id' => '请输入身份类型',
                'package_id' => '请输入套餐item_id',
            ];

            foreach ($required as $key => $require) {
                if(!isset($data[$key]) || empty($data[$key])){
                    throw new ValidatorException($require, 4002);
                }
            }

            /** @var PermissionLogic $PermissionLogic */
            $PermissionLogic = BeanFactory::getBean(PermissionLogic::class);
            $result = $PermissionLogic->packageModules($data);
            return Response::Info($result);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 通过租户id获取套餐
     * @param array $data
     * @return array
     */
    public function tenantPackages(array $data): array {
        try {
            //验证字段
            $required = [
                'user_item_id' => '请输入用户item_id',
                'identity_id' => '请输入身份类型',
                'tenant_id' => '请输入租户item_id',
            ];

            foreach ($required as $key => $require) {
                if(!isset($data[$key]) || empty($data[$key])){
                    throw new ValidatorException($require, 4002);
                }
            }

            /** @var PermissionLogic $PermissionLogic */
            $PermissionLogic = BeanFactory::getBean(PermissionLogic::class);
            $result = $PermissionLogic->tenantPackages($data);
            foreach ($result as &$e){
                $e['startAt'] = isset($e['startAt'])?date('Y-m-d H:i:s', $e['startAt']):'';
                $e['endAt'] = isset($e['endAt'])?date('Y-m-d H:i:s', $e['endAt']):'永久';
            }
            return Response::Info($result);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 租户套餐
     * @param array $data
     * @return array
     */
    public function tenantModifyPackages(array $data): array
    {
        try{
            $tenant_item_id = $data['tenant_item_id']??null;
            //授权套餐id
            $attached_package_item_ids = $data['attached_package_item_ids']??[];

            //解除套餐id
            $detached_package_item_ids = $data['detached_package_item_ids']??[];

            //计算时间
            $num = $data['num']??null;
            $num = intval($num);
            $unit = $data['unit']??'day';

            if(!$tenant_item_id || (!$attached_package_item_ids && !$detached_package_item_ids)){
                Response::FatalError(ErrorConstant::VALIDATE_ERROR_CODE, '请求参数错误');
            }

            //新增套餐但是没有传套餐时长
            if($attached_package_item_ids && (!$num || $num <= 0)){
                Response::FatalError(ErrorConstant::VALIDATE_ERROR_CODE, '请求参数错误');
            }

            $data['item_id'] = create_item_id(uuid());

            //计算开始和结束时间
            $time = count_date($num, $unit);
            $data['start_at'] = time();
            $data['end_at']   = time() + $time;

            //去掉多余数据
            unset($data['num'], $data['unit']);

            /** @var PermissionLogic $PermissionLogic */
            $PermissionLogic = BeanFactory::getBean(PermissionLogic::class);
            $result = $PermissionLogic->tenantModifyPackages($data);


            return Response::Info($result);
        }
        catch (\Exception $e){
            DB::rollBack();
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 租户权限列表
     * @param array $data
     * @return array
     */
    public function tenantPermissionsList(array $data): array
    {
        try {
            $condition = [
                'p' => intval($data['p']??1),
                'per' => intval($data['per']??10)
            ];

            /** @var TenantPermissionsDao $TenantPermissionsDao */
            $TenantPermissionsDao = BeanFactory::getBean(TenantPermissionsDao::class);
            $result = $TenantPermissionsDao->getList($condition);
            if(!isset($result['data']) || !$result['data']){
                throw new ValidatorException('查询无果');
            }

            //查询结果
            return Response::Info($result);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 模块管理列表
     * @param array $data
     * @return array
     */
    public function moduleList(array $data): array
    {
        try {
            $condition = [
                'p' => $data['p']??1,
                'per' => $data['per']??1
            ];

            /** @var ModuleDao $ModuleDao */
            $ModuleDao = BeanFactory::getBean(ModuleDao::class);
            $result = $ModuleDao->getList($condition);
            if(!isset($result['data']) || !$result['data']){
                throw new ValidatorException('查询无果');
            }

            //查询结果
            return Response::Info($result);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 套餐管理列表
     * @param array $data
     * @return array
     */
    public function packageList(array $data): array
    {
        try {
            $condition = [
                'p' => $data['p']??1,
                'per' => $data['per']??1
            ];

            /** @var PackageDao $PackageDao */
            $PackageDao = BeanFactory::getBean(PackageDao::class);
            $result = $PackageDao->getList($condition);
            if(!isset($result['data']) || !$result['data']){
                throw new ValidatorException('查询无果');
            }

            //查询结果
            return Response::Info($result);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 租户人员管理列表
     * @param array $data
     * @return array
     */
    public function tenantList(array $data): array
    {
        try {
            $condition = [
                'page' => $data['page']??1,
                'pageSize' => $data['pageSize']??10
            ];

            isset($data['name']) && $data['name']?$condition['where'][] = ['legal_name', 'like',  '%'.$data['name'].'%']:'';
            isset($data['cname']) && $data['cname']?$condition['where'][] = ['name', 'like',  '%'.$data['cname'].'%']:'';
            isset($data['account']) && $data['account']?$condition['where'][] = ['account', 'like',  '%'.$data['account'].'%']:'';

            /** @var TenantDao $TenantDao */
            $TenantDao = BeanFactory::getBean(TenantDao::class);
            $result = $TenantDao->getListFormat($condition);
            if(!isset($result['list']) || !$result['list']){
                throw new ValidatorException('查询无果');
            }

            //查询结果
            return Response::Info($result);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 查询租户人员以及自己
     * @param array $data
     * @return array
     */
    public function tenantMemberList(array $data): array {
        try {
            $condition = [
                'page' => $data['page']??1,
                'pageSize' => $data['pageSize']??10
            ];

            if(isset($data['where']) && $data['where']){
                $condition['where'] = $data['where'];
            }

            /** @var PermissionLogic $logic */
            $logic = BeanFactory::getBean(PermissionLogic::class);
            $result = $logic->tenantMemberList($condition);

            //查询结果
            return Response::Info($result);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }
    /**
     * 模块健康度
     * @param array $data
     * @return array
     */
    public function moduleHealth(array $data): array {
        try {
            //验证字段
            $required = [
                'user_item_id' => '请输入用户item_id',
                'identity_id' => '请输入身份类型',
                'tenant_id' => '请输入租户item_id',
            ];

            foreach ($required as $key => $require) {
                if(!isset($data[$key]) || empty($data[$key])){
                    throw new ValidatorException($require, 4002);
                }
            }

            /** @var PermissionLogic $PermissionLogic */
            $PermissionLogic = BeanFactory::getBean(PermissionLogic::class);
            $result = $PermissionLogic->moduleHealth($data);

            //查询结果
            return Response::Info($result);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }
}
